package com.cccyy.data;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.HashMap;
import java.util.Map;

public class JsonToMap {
    public static void main(String[] args) {
        //
        String result =
                "{\"user_info\":\"{\"appeidcode\":\"6tRNlJ8VMtSGGm7+M8oPy4RGDsQXQMzKJvQDy6jrkokxMDAw\"}\",\"similarity\":\"89.00\",\"_RejCode\":\"000000\",\"biz_sequence_id\":\"f11d3bddb71748c6ae38c5f171a30716\",\"_RejMessage\":\"成功\"}";

//    String result =
//        "{\"user_info\":\"{'appeidcode':'6tRNlJ8VMtSGGm7+M8oPy4RGDsQXQMzKJvQDy6jrkokxMDAw''}\",\"similarity\":\"89.00\",\"_RejCode\":\"000000\",\"biz_sequence_id\":\"f11d3bddb71748c6ae38c5f171a30716\",\"_RejMessage\":\"成功\"}";

        Map resultMap = (Map) JSON.parseObject(result, HashMap.class);
        Object rejCode = resultMap.get("_RejCode");
        System.out.println(rejCode);

        JSONObject jsonObject = JSON.parseObject("{ \"key\": \"value\", \"anotherKey\": 123 }");
        Map<String, Object> map = jsonObject.getObject("", Map.class);

        Map<String, Object> map2 = jsonObject.getInnerMap();


        ObjectMapper mapper = new ObjectMapper();
        // 已有的JSONObject实例
        try {
            Map<String, Object> map3 = mapper.readValue(jsonObject.toJSONString(), new TypeReference<Map<String, Object>>(){});
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

        /*如果是org.json库的JSONObject，可以遍历其键值对并手动填充到HashMap中*/
//        JSONObject jsonObject2 = new JSONObject("{ \"key\": \"value\", \"anotherKey\": 123 }");
//        Map<String, Object> map = new HashMap<>();
//        Iterator<String> keys = jsonObject2.keys();
//        while (keys.hasNext()) {
//            String key = keys.next();
//            Object value = jsonObject2.get(key);
//            map.put(key, value);
//        }
    }
}
